package com.glsc.ngateway.flowable.config;

import org.springframework.boot.autoconfigure.mail.MailProperties;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.JavaMailSenderImpl;

import java.util.Map;
import java.util.Properties;

@Configuration
public class MailConfig {
    @Bean
    @Primary
    @ConfigurationProperties(prefix = "spring.mail")
    public MailProperties mailSenderProperties() {
        return new MailProperties();
    }

    @Bean
    @Primary
    @ConfigurationProperties(prefix = "spring.mail")
    public JavaMailSender mailSender(MailProperties mailSender2Properties) {
        JavaMailSenderImpl sender = new JavaMailSenderImpl();
        this.applyProperties(sender, mailSender2Properties);
        return sender;
    }


    private void applyProperties(JavaMailSenderImpl sender, MailProperties properties) {
        sender.setHost(properties.getHost());
        if (properties.getPort() != null) {
            sender.setPort(properties.getPort());
        }
        sender.setUsername(properties.getUsername());
        sender.setPassword(properties.getPassword());
        sender.setProtocol(properties.getProtocol());
        if (properties.getDefaultEncoding() != null) {
            sender.setDefaultEncoding(properties.getDefaultEncoding().name());
        }
        if (!properties.getProperties().isEmpty()) {
            sender.setJavaMailProperties(asProperties(properties.getProperties()));
        }
    }

    private Properties asProperties(Map<String, String> source) {
        Properties properties = new Properties();
        properties.putAll(source);
        return properties;
    }
}
